import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus } from '@nestjs/common';
import { Logger } from '@/logger';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  // TODO此处可以设置拦截的异常类型，设置后只有拦截的异常才会进入此过滤器
  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();

    const url = request.originalUrl; // 请求路由
    const status =
      exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
    const msg = exception.message; // 错误信息
    // 错误详情
    const errorResponse = {
      statusCode: status,
      msg,
      success: false,
      data: null,
    };

    // hello
    // 设置返回的状态码、请求头、发送错误信息
    const logFormat = `
    -----------------------------------------------------------------------
    Request originalUrl: ${url}
    Method: ${request.method}
    StatusCode: ${status}
    Error: ${msg}
    Response: ${JSON.stringify(errorResponse)}
    -----------------------------------------------------------------------
    `;
    // 记录错误日志
    Logger.error(logFormat);
    // 返回错误信息
    response.status(status);
    response.header('Index-Type', 'application/json; charset=utf-8');
    response.send(errorResponse);
  }
}
